<template>
  <div class="animated-counter">
    <div class="counter-value" ref="counterRef">{{ displayValue }}</div>
    <div class="counter-unit" v-if="unit">{{ unit }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { CountUp } from 'countup.js'

const props = defineProps({
  value: {
    type: Number,
    default: 0
  },
  duration: {
    type: Number,
    default: 2
  },
  unit: {
    type: String,
    default: ''
  },
  decimals: {
    type: Number,
    default: 0
  },
  prefix: {
    type: String,
    default: ''
  },
  suffix: {
    type: String,
    default: ''
  }
})

const counterRef = ref(null)
const displayValue = ref(0)
let countUp = null

onMounted(() => {
  initCountUp()
})

watch(() => props.value, (newVal) => {
  if (countUp) {
    countUp.update(newVal)
  }
})

const initCountUp = () => {
  const options = {
    duration: props.duration,
    decimalPlaces: props.decimals,
    prefix: props.prefix,
    suffix: props.suffix,
    useEasing: true,
    useGrouping: true,
    onCompleteCallback: () => {
      displayValue.value = props.value
    }
  }
  
  countUp = new CountUp(counterRef.value, props.value, options)
  if (!countUp.error) {
    countUp.start()
  }
}
</script>

<style scoped>
.animated-counter {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.counter-value {
  font-size: inherit;
  font-weight: inherit;
  color: inherit;
}

.counter-unit {
  font-size: 0.8em;
  opacity: 0.8;
}
</style> 